<?php
declare (strict_types=1);

namespace app\common\job;

use app\admin\model\media\Website as WebsiteModel;
use app\admin\model\media\Module as ModuleModel;
use app\admin\model\media\Article as ArticleModel;

use think\facade\Db;
use think\queue\Job;
use app\common\library\media\Crawler;

class Media
{
    /**
     * @var WebsiteModel
     */
    private $WebsiteModel;
    /**
     * @var ModuleModel
     */
    private $ModuleModel;
    /**
     * @var ArticleModel
     */
    private $ArticleModel;

    public function __construct()
    {
        $this->WebsiteModel = new WebsiteModel;
        $this->ModuleModel = new ModuleModel;
        $this->ArticleModel = new ArticleModel;
    }

    /**
     * @param Job $job
     * @param $data
     */
    public function fire(Job $job, $data)
    {

        //启动redis
        //redis-server.exe redis.windows.conf

        //启动队列
        //php think queue:work --queue MediaQueue --tries=3

        //任务名称
        $jobName = $job->getName();
        $jobId = $job->getJobId();

        $result = $this->latest($data);
        if ($result) {
            echo "执行成功\n";
            //任务执行成功后，删除任务
            $job->delete();

        } else {
            echo "执行失败\n";
            if ($job->attempts() > 3) {
                //通过这个方法可以检查这个任务已经重试了几次了
                //直到达到最大重试次数后失败后，执行failed方法
                $job->delete();
            } else {
                // 重新发布这个任务
                //$delay = 60 * 60 * $job->attempts();
                $delay = pow(60, $job->attempts());

                $job->release($delay); //$delay为延迟时间
            }
        }
        Db::__destruct();
    }

    /*
     * 采集网站最新文章
     */
    protected function latest($data)
    {
        $module_id = $data['module_id'];
        $module = $this->ModuleModel->where('id', '=', $module_id)->find();

        if ($module) {
            //添加下一阶段
            $delay = $module['times'];
            add_media_queue($data, $delay);

            if ($module['status'] == 1 && $module['error_count'] < 3) {
                $config = json_decode($module['rules'], true);
                $crawler = new Crawler($config);
                $url = isset($config['url']) ? $config['url'] : $module['url'];
                $html = $crawler->getWebsiteHtml($url);
                $dataList = $crawler->getHtmlData();
                if (empty($dataList) || isset($dataList[0]['title']) == false) {
                    $module->inc('error_count', 1);
                    $module->save(['error_msg' => '采集规则无效']);
                } else {
                    $module->save(['error_count' => 0, 'error_msg' => '']);
                    $this->ArticleModel->saveArticleList($dataList, $module);
                }
            }
        }
        return true;
    }

    public function failed($data)
    {

        // ...任务达到最大重试次数后，失败了
    }

}